import { defineStore } from "pinia";
import { login, logout, checkLogin } from "@/api/login";
import { ElMessage } from "element-plus";
import { useRouteStore } from "./route";
import router from "@/router";
import { getSession, setSession, removeAllItem } from "@/utils/storage";
import pinia from "@/main";

export const useUserStore = defineStore("USER", {
  state: () => {
    return {
      // userInfo: getSession("__userInfo__", {}),
      userInfo: {},
    };
  },
  actions: {
    loginFn(value) {
      login(value).then(async ({ data }) => {
        // console.log(data);
        if (data.code == 0) {
          this.userInfo = data.data;
          setSession("__userInfo__", data.data);
          ElMessage.success(data.txt);
          const routeStore = useRouteStore();
          await routeStore.getMenuRouteFn();
          router.push("/");
        } else {
          //登录失败
          ElMessage.error(data.txt);
        }
      });
    },
    logoutFn() {
      logout().then(({ data }) => {
        if (!data.code) {
          // 退出登录成功
          // 清空本地存储
          // window.localStorage.clear();
          // window.sessionStorage.clear();
          // this.$reset();
          removeAllItem();

          // 清空大菠萝的数据
          const allStore = [...pinia._s.values()];
          allStore.forEach((item) => {
            item.$reset();
          });

          ElMessage.success(data.txt);
          router.push("/login");
        } else {
          ElMessage.success("退出登录失败");
        }
      });
    },
    // 验证登录
    checkLoginFn() {
      return new Promise((res, rej) => {
        checkLogin().then(({ data }) => {
          if (!data.code) {
            // 已登录
            this.userInfo = data.data;
            setSession("__userInfo__", data.data);
          }
          res(data.code);
        });
      });
    },
  },
});
